<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>用户管理</title>
    <link href="bootstrap/css/bootstrap.css" rel="stylesheet">
</head>
<body>
<div class="container mt-5">
    <h2>用户管理</h2>
    <button class="btn btn-primary mb-3" data-bs-toggle="modal" data-bs-target="#userModal" onclick="openAddModal()">新增用户</button>
    <table class="table table-bordered">
        <thead>
        <tr>
            <th>ID</th>
            <th>用户名</th>
            <th>年龄</th>
            <th>年级</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody id="userTableBody">
        <!-- 数据动态填充 -->
        </tbody>
    </table>
</div>

<!-- 用户新增/编辑模态框 -->
<div class="modal fade" id="userModal" tabindex="-1" aria-labelledby="userModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <form id="userForm" onsubmit="submitUserForm(event)">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="userModalLabel">新增用户</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" id="userId">
                    <div class="mb-3">
                        <label for="name" class="form-label">用户名</label>
                        <input type="text" class="form-control" id="name" required>
                    </div>
                    <div class="mb-3">
                        <label for="age" class="form-label">邮箱</label>
                        <input type="text" class="form-control" id="age" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </div>
        </form>
    </div>
</div>

<script src="bootstrap/js/bootstrap.bundle.js"></script>
<script>
    let editingId = null;

    // 获取用户列表
    function fetchUsers() {
        fetch('/api/user/list')
            .then(res => res.json())
            .then(data => {
                console.log(data)
                const tbody = document.getElementById('userTableBody');
                tbody.innerHTML = '';
                data.data.forEach(user => {
                    tbody.innerHTML += `
                    <tr>
                        <td>${user.id}</td>
                        <td>${user.name}</td>
                        <td>${user.age}</td>
                        <td>${user.gender}</td>
                        <td>
                            <button class="btn btn-sm btn-warning" onclick="openEditModal(${user.id}, '${user.name}', '${user.age}')">编辑</button>
                            <button class="btn btn-sm btn-danger" onclick="deleteUser(${user.id})">删除</button>
                        </td>
                    </tr>
                `;
                });
            });
    }

    // 打开新增用户模态框
    function openAddModal() {
        editingId = null;
        document.getElementById('userModalLabel').innerText = '新增用户';
        document.getElementById('userId').value = '';
        document.getElementById('name').value = '';
        document.getElementById('age').value = '';
    }

    // 打开编辑用户模态框
    function openEditModal(id, name, age) {
        editingId = id;
        document.getElementById('userModalLabel').innerText = '编辑用户';
        document.getElementById('userId').value = id;
        document.getElementById('name').value = name;
        document.getElementById('age').value = age;
        new bootstrap.Modal(document.getElementById('userModal')).show();
    }

    // 提交表单（新增或编辑）
    function submitUserForm(event) {
        event.preventDefault();
        const id = document.getElementById('userId').value;
        const name = document.getElementById('name').value;
        const age = document.getElementById('age').value;
        const user = { name, age };

        if (editingId) {
            // 编辑
            fetch(`/api/user/${editingId}`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(user)
            }).then(() => {
                bootstrap.Modal.getInstance(document.getElementById('userModal')).hide();
                fetchUsers();
            });
        } else {
            // 新增
            fetch('/api/user', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(user)
            }).then(() => {
                bootstrap.Modal.getInstance(document.getElementById('userModal')).hide();
                fetchUsers();
            });
        }
    }

    // 删除用户
    function deleteUser(id) {
        if (confirm('确定要删除该用户吗？')) {
            fetch(`/api/user/${id}`, { method: 'DELETE' })
                .then(() => fetchUsers());
        }
    }

    // 页面加载时获取用户列表
    window.onload = fetchUsers;
</script>
</body>
</html>
